/*
 * Copyright (C) 2024 InConnect. All rights reserved.
 */
package auth

import (
	"dqbasepkg/log"
	"dqbasepkg/utils"
	"encoding/xml"
	"net/http"
	"strconv"
)

type AuthConfig struct {
	Pid   int64  `xml:"pid,attr"`
	Ts    int64  `xml:"ts,attr"`
	Uc    int64  `xml:"uc,attr"`
	Flags int32  `xml:"flags,attr"`
	Err   int32  `xml:"error,attr"`
	Sign  string `xml:"sign,attr"`
}

func HandleAuth(w http.ResponseWriter, r *http.Request) {
	ac_item := r.URL.Query().Get("ac")
	sh_item := r.URL.Query().Get("sh")
	at_item := r.URL.Query().Get("at")
	uc_item := r.URL.Query().Get("uc")
	pid_item := r.URL.Query().Get("pid")
	ts_item := r.URL.Query().Get("ts")
	sign_item := r.URL.Query().Get("sign")

	log.Info("handle auth", log.String("q_ac", ac_item), log.String("q_sh", sh_item), log.String("q_at", at_item), log.String("q_uc", uc_item), log.String("q_pid", pid_item), log.String("q_ts", ts_item), log.String("q_sign", sign_item), log.String("r_ip", utils.GetHttpRequestRealIP(r)))
	at, err := strconv.Atoi(at_item)
	if err != nil || at < 0 {
		log.Warn("invalid at", log.ErrorT(err))
	}

	uc, err := strconv.Atoi(uc_item)
	if err != nil || uc < 0 {
		log.Warn("invalid uc", log.ErrorT(err))
	}

	pid, err := strconv.ParseInt(pid_item, 10, 64)
	if err != nil {
		log.Warn("invalid pid", log.ErrorT(err))
	}

	ts, err := strconv.ParseInt(ts_item, 10, 64)
	if err != nil {
		log.Warn("invalid ts", log.ErrorT(err))
	}

	// TODO: check sign_item
	config := AuthConfig{}
	config.Pid = pid
	config.Ts = ts
	config.Uc = 0
	config.Flags = 0
	config.Err = 0
	str := ""
	str += strconv.FormatInt(config.Pid, 10)
	str += "_"
	str += strconv.FormatInt(config.Ts, 10)
	str += "_"
	str += strconv.FormatInt(config.Uc, 10)
	str += "_"
	if config.Flags != 0 {
		str += strconv.Itoa(int(config.Flags))
		str += "_"
	}
	str += strconv.Itoa(int(config.Err))
	str += "_"
	str += "35a83b32f389c8"
	config.Sign = utils.StringToMd5Hex(str)

	data, err := xml.Marshal(&config)
	if err != nil {
		log.Warn("xml.Marshal error", log.ErrorT(err))
		data = []byte("<root error=\"-1\"></root>")
	}

	contentLength := len(data)
	wh := w.Header()
	wh.Set("Content-Type", "application/xml")
	wh.Set("Content-Length", strconv.Itoa(contentLength))
	w.Write(data)
}
